<template>
  <view>
    <button @click="getUserInfo" type="primary">微信登录</button>
  </view>
</template>

<script>
export default {
  async onLoad () {
    const [error, data] = await uni.login()
    if (!error) {
      console.log(data)
      // code参数存储到this
      this.code = data.code
    }
  },
  methods: {
    async getUserInfo () {
      const [error, userInfo] = await uni.getUserProfile({ desc: '获取微信用户信息' })
      if (!error) {
        console.log(userInfo)
        this.login(userInfo)
      }
    },
    // 调用接口登录
    async login (user) {
      // 登录所需参数
      const { encryptedData, iv, rawData, signature } = user
      // 微信用户登录凭证=》code=>会出现：Error: Illegal Buffer问题
      // const [err, c] = await uni.login()
      // this.code = c.code
      let { msg, data } = await this.request({
        url: "/api/public/v1/users/wxlogin",
        method: "post",
        data: {
          encryptedData,
          iv,
          rawData,
          signature,
          code: this.code
        }
      })
      // 存储token，返回上次访问页面
      uni.setStorageSync("token", data.token)
      uni.navigateBack()

    }
  },
}
</script>

<style lang="scss" scoped>
button {
  width: 600rpx;
  margin: 200rpx auto 0;
}
</style>